import {useEffect, useMemo} from "react";
import fingerprint from "@fingerprintjs/fingerprintjs";
import {getInfo, setToken, updateInfo} from "@/reducer/user";
import {useDispatch, useSelector} from "react-redux";
import {Dispatch} from "@reduxjs/toolkit";
import {CommonDispatch} from "@/store";
import {loginByDeviceId} from "@/api/user";
import {useNavigate} from "react-router";
import useSetTitleByLocation from "@/hooks/useSetTitleByLocation";
import "./index.scss";

export default function VisitorAuth(props: any): any {
  const dispatch: CommonDispatch = useDispatch<Dispatch>();
  const user: any = useSelector((state: any) => state.user);
  const {title, isBack} = useSetTitleByLocation();
  const navigate = useNavigate();

  async function handleLoad() {
    if (!user.token) {
      const fingerprintRes = await fingerprint.load();
      const deviceInfo = await fingerprintRes.get();
      // 记录指纹id以及当前浏览器信息（应该会有手机型号）
      const res = await loginByDeviceId({deviceId: deviceInfo.visitorId, userAgent: navigator.userAgent});
      dispatch(setToken(res.data));
    }
    // 获取用户消息
    await dispatch(getInfo());
    // 没有的话更新
    if (!user?.info?.userAgent) {
      debugger;
      dispatch(updateInfo({userAgent: navigator.userAgent}));
    }
  }

  useEffect(() => {
    handleLoad();
  }, []);

  function handleBack() {
    navigate(-1);
  }

  return useMemo(
    () =>
      user.token ? (
        <div className={"VisitorAuth"}>
          {title && (
            <div className={"VisitorAuth-header"}>
              {isBack && <span onClick={handleBack}>返回</span>}
              <span className={"title"}>{title}</span>
            </div>
          )}
          <div className={"VisitorAuth-body"}>{props.children}</div>
        </div>
      ) : (
        ""
      ),
    [props.children, user.token, title]
  );
}
